<template>
  <el-form :inline="true">
    <el-row>
      <el-col :span="4">
        <el-form-item>
          <el-select v-model="NFTstate" placeholder="状态" @change="changeNftState" clearable="true">
            <el-option label="已存证" value="已存证"/>
            <el-option label="未存证" value="未存证"/>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="7">
        <el-form-item>
          <el-select v-model="NFTtype" placeholder="类别" @change="changeNftType" clearable="true">
            <el-option label="文字作品" value="文字作品" />
            <el-option label="摄影作品" value="摄影作品" />
            <el-option label="美术作品" value="美术作品" />
            <el-option label="音乐作品" value="音乐作品" />
            <el-option label="影视作品" value="影视作品" />
          </el-select>
        </el-form-item>
      </el-col>


      <el-col :span="5">
        <el-form-item>
          <el-input v-model="NFTname" placeholder="搜索作品名称" clearable="true" @clear="getdata"/>
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-form-item>
          <el-button color="#626aef"
                     :dark="isDark"
                     plain :icon="Search" @click="search">搜索</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-form-item>
          <el-button @click="addNft" color="#626aef"
                     :dark="isDark"
                     plain>添加NFT</el-button>
        </el-form-item>
      </el-col>

      <el-col :span="4">
        <el-form-item>
          <el-button @click="getdata" color="#626aef"
                     :dark="isDark"
                     plain>刷新</el-button>
        </el-form-item>
      </el-col>

    </el-row>
  </el-form>

  <el-table :data="TableData" style="width: 1190px"
            :header-cell-style="{background:'#703CF6',color:'#fdfdfd',textAlign: 'center'}"
            :cell-style="{ textAlign: 'center' }"
            v-loading="loading"
  >

    <el-table-column prop="name" label="NFT名称" width="120"/>

    <el-table-column prop="type" label="NFT类别" width="120">
      <template v-slot="scope">
        <el-tag type="primary" v-if="scope.row.type=='文字作品'">{{ scope.row.type }}</el-tag>
        <el-tag type="success" v-if="scope.row.type=='摄影作品'">{{ scope.row.type }}</el-tag>
        <el-tag type="danger" v-if="scope.row.type=='美术作品'">{{ scope.row.type }}</el-tag>
        <el-tag type="info" v-if="scope.row.type=='音乐作品'">{{ scope.row.type }}</el-tag>
        <el-tag type="warning" v-if="scope.row.type=='影视作品'">{{ scope.row.type }}</el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="createdTime" label="创建时间" width="260"/>

    <el-table-column label="标签" width="160">
      <template v-slot="scope">
        <el-tag type="warning" v-if="scope.row.tag1">{{ scope.row.tag1 }}</el-tag>
        <el-tag type="success" v-if="scope.row.tag2">{{ scope.row.tag2 }}</el-tag>
        <el-tag type="danger" v-if="scope.row.tag3">{{ scope.row.tag3 }}</el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="fileName" label="存证文件" width="200">
      <template v-slot="scope">
        <!--        scope.row.fileDownloadUrl-->
        <el-link type="primary" :href=scope.row.fileDownloadUrl>{{ scope.row.fileName }}</el-link>
      </template>
    </el-table-column>

    <el-table-column prop="status" label="状态" width="160">
      <template v-slot="scope">
        <el-tag type="primary" v-if="scope.row.status=='已存证'">已存证</el-tag>
        <el-tag type="danger" v-if="scope.row.status=='未存证'">未存证</el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="operation" label="操作" width="170">
      <template v-slot="scope">
        <el-link type="default" v-if="scope.row.status=='已存证'" disabled>撤销</el-link>
        <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="是否确定撤销?"
            @confirm="revocation(scope.row.id)"
        >
          <template #reference>
            <el-link type="primary" v-if="scope.row.status=='未存证'">撤销</el-link>
          </template>
        </el-popconfirm>

        <span class="seat"></span>
        <el-link type="default" @click="upChain(scope.row.id)" v-if="scope.row.status=='已存证'" disabled>上链</el-link>
        <el-link type="primary" @click="upChain(scope.row.id)" v-if="scope.row.status=='未存证'"  v-loading.fullscreen.lock="fullscreenLoading">上链</el-link>
        <span class="seat"></span>
        <el-link type="primary" @click="showDetail(scope.row.fileHash,scope.row.id)">查看详情</el-link>

      </template>
    </el-table-column>

  </el-table>

  <el-dialog
      v-model="uploadNftVisible"
      title="上传NFT" width="30%"
      align-center
      class="dialog"
  >
    <el-card class="card">
      <template #header>
        <span>文件信息</span>
      </template>
      <el-form
          label-width="200px"
          :model="upLoadNftForm"
          ref="upLoadNftForm"
          :rules="upLoadNftRule"
      >

        <el-form-item label="作品名称" prop="name">
          <el-input v-model="upLoadNftForm.name"/>
        </el-form-item>

        <el-form-item label="作品类别" prop="type">
          <el-select placeholder="请选择作品类别" v-model="upLoadNftForm.type">
            <el-option
                v-for="item in nftTypeOptions"
                :label="item.key"
                :key="item.key"
                :value="item.val"/>
          </el-select>
        </el-form-item>

        <el-form-item label="作品简介" prop="introduction">
          <el-input type="textarea" v-model="upLoadNftForm.introduction"/>
        </el-form-item>

        <el-form-item label="所有权人身份类别" >
          <!--          <el-select v-model="upLoadNftForm.copyrightOwnerType">-->
          <!--            <el-option-->
          <!--                v-for="item in copyrightOwnerTypeOptions"-->
          <!--                :label="item.key"-->
          <!--                :key="item.key"-->
          <!--                :value="item.val"/>-->
          <!--          </el-select>-->

          <span>自然人</span>
          <el-form-item label="所有权人名称" >
            <span>{{this.copyrightOwnerName}}</span>
          </el-form-item>
        </el-form-item>
        <el-form-item label="所有权人证件类型" >
          <span>身份证</span>
          <!--          <el-select placeholder="" v-model="upLoadNftForm.idType">-->
          <!--            <el-option-->
          <!--                v-for="item in idTypeOptions"-->
          <!--                :label="item.key"-->
          <!--                :key="item.key"-->
          <!--                :value="item.val"/>-->
          <!--          </el-select>-->

          <el-form-item label="所有权人证件号码" >
            <span>{{this.copyrightOwnerId}}</span>
          </el-form-item>
        </el-form-item>

        <el-form-item label="添加标签1" prop="tag1">
          <el-select placeholder="" v-model="upLoadNftForm.tag1">
            <el-option
                v-for="item in tagOptions"
                :label="item"
                :key="item"
                :value="item"/>
          </el-select>
          <el-form-item label="添加标签2" prop="tag2">
            <el-select placeholder="" v-model="upLoadNftForm.tag2">
              <el-option
                  v-for="item in tagOptions"
                  :label="item"
                  :key="item"
                  :value="item"/>
            </el-select>
          </el-form-item>
        </el-form-item>

        <el-form-item label="添加标签3" prop="tag3">
          <el-select placeholder="" v-model="upLoadNftForm.tag3">
            <el-option
                v-for="item in tagOptions"
                :label="item"
                :key="item"
                :value="item"/>
          </el-select>
        </el-form-item>

        <el-form-item class="bottom-but" label="存证文件" prop="fileList">
          <el-upload
              class="uploadFile"
              action="http://120.48.51.66:8081/user/addNFT"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="1"
              :on-change="handChange"
              :on-exceed="handleExceed"
              :auto-upload="false"
              :file-list="upLoadNftForm.fileList"
              show-file-list
          >
            <el-button size="small" color="#626aef"
                       :dark="isDark"
                       plain>点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-card>

    <template #footer>
      <span>
        <el-button class="cancel-but" @click="uploadNftVisible=false">取消</el-button>
      <el-button class="split-upload-but" @click="go2Split">拆分上传</el-button>
      <el-button class="upload-but" @click="upLoad">确认上传</el-button>

      </span>
    </template>
  </el-dialog>

  <!--  拆分上传-->

  <el-dialog
      v-model="uploadNftVisible2"
      title="上传NFT" width="30%"
      align-center
      class="dialog"
  >
    <el-card class="card">
      <template #header>
        <span>文件信息</span>
      </template>
      <el-form
          label-width="200px"
          :model="upLoadNftForm"
          ref="upLoadNftForm"
          :rules="upLoadNftRule"
      >

        <el-form-item label="作品名称" prop="name">
          <el-input v-model="upLoadNftForm.name"/>
        </el-form-item>

        <el-form-item label="作品类别" prop="type">
          <el-select placeholder="请选择作品类别" v-model="upLoadNftForm.type">
            <el-option
                v-for="item in nftTypeOptions2"
                :label="item.key"
                :key="item.key"
                :value="item.val"/>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="文件种类" prop="type">-->
<!--          <el-select placeholder="请选择文件种类" v-model="workKind">-->
<!--            <el-option-->
<!--                v-for="item in nftKindOptions"-->
<!--                :label="item.key"-->
<!--                :key="item.key"-->
<!--                :value="item.val"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <el-form-item label="作品简介" prop="introduction">
          <el-input type="textarea" v-model="upLoadNftForm.introduction"/>
        </el-form-item>


        <el-form-item label="所有权人身份类别" >
          <span>自然人</span>
          <el-form-item label="所有权人名称" >
            <span>{{this.copyrightOwnerName}}</span>
          </el-form-item>
        </el-form-item>
        <el-form-item label="所有权人证件类型" >
          <span>身份证</span>
          <el-form-item label="所有权人证件号码" >
            <span>{{this.copyrightOwnerId}}</span>
          </el-form-item>
        </el-form-item>

        <el-form-item label="添加标签" prop="tag1">
          <el-select placeholder="" v-model="upLoadNftForm.tag1">
            <el-option
                v-for="item in tagOptions"
                :label="item"
                :key="item"
                :value="item"/>
          </el-select>
        </el-form-item>


        <el-form-item class="bottom-but" label="存证文件" prop="fileList">
          <el-upload
              class="uploadFile"
              action="http://120.48.51.66:8081/work/addNftPieces"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="1"
              :on-change="handleChange2"
              :on-exceed="handleExceed"
              :auto-upload="false"
              :file-list="this.upLoadNftForm.fileList"
              show-file-list
          >
            <el-button size="small" color="#626aef"
                       :dark="isDark"
                       plain>拆分上传</el-button>
          </el-upload>
        </el-form-item>
        <div class="choiceOfSplit">
          <ImgCutter
              v-if="(this.upLoadNftForm.type=='1') || (this.upLoadNftForm.type=='5')"
              :tool="false"
              :img-move="false"
              :move-able="false"
              :size-change="false"
              :toolBoxOverflow="false"
              :cut-height = this.height
              :cut-width = this.width
              :scale-able = "false"
              label = "拆分效果查看"
              class="imgCut"
          >
          </ImgCutter>
          <el-button v-else-if="this.upLoadNftForm.type==''">请选择文件种类</el-button>
          <el-button v-else>
            <div style="width: 400px">
              <span class="demonstration">滑动选择拆分份数</span>
              <el-slider v-model="numOfSplit" :step="1" show-stops :max="5" :min="2"/>
            </div>
          </el-button>
        </div>

      </el-form>
    </el-card>

    <template #footer>
      <span>
        <el-button class="cancel-but" @click="uploadNftVisible2=false">取消</el-button>
        <el-button class="upload-but" @click="upLoad2">确认上传</el-button>
      </span>
    </template>
  </el-dialog>


  <!--查看详情-->
  <el-drawer v-model="drawer" :with-header="true" title="NFT详情" size="40%">
    <el-tabs class="drawerTab"  type="border-card">
      <el-tab-pane label="存证详细信息">
        <el-descriptions
            direction="vertical"
            :column="1"
            :size="size"
            border
        >
          <el-descriptions-item label="所有者姓名">{{ this.nftObj.copyrightOwnerName }}</el-descriptions-item>
          <el-descriptions-item label="所有者证件号码">{{ this.nftObj.copyrightOwnerId }}</el-descriptions-item>
          <el-descriptions-item label="上传时间">{{ this.nftObj.createdTime }}</el-descriptions-item>
          <el-descriptions-item label="文件介绍">{{ this.nftObj.introductionUrl }}</el-descriptions-item>
          <el-descriptions-item label="文件哈希">{{ this.detail }}</el-descriptions-item>
          <el-descriptions-item label="上链交易哈希">{{ this.nftObj.chainHash }}</el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <el-tab-pane label="存证证明文件">
        <el-button
            color="#626aef"
            :dark="isDark"
            plain
            @click="downloadCer"
        >
          <el-icon size="large"><Download /></el-icon>
          下载文件</el-button>
        <el-alert
            title="存证证明文件预览"
            type="info"
            description="此文件为在本平台上链的认证，请下载并保存在本地"
            show-icon
            :closable="false"
            style="margin-top: 10px"
        />
        <VuePdfEmbed class="CerPdf" :source="this.CerUrl"/>
      </el-tab-pane>
    </el-tabs>
  </el-drawer>
</template>

<script>
import {ElMessage} from 'element-plus'
// eslint-disable-next-line no-unused-vars
import axios from "axios";
import conflux from '../conflux/conflux'
import confluxPortal from "@/conflux/conflux-portal";
// eslint-disable-next-line no-unused-vars
import {ContractCopyright, ContractCopyrightSystemTransactions, ContractHnuCoin} from "@/conflux/conflux";
import ImgCutter from 'vue-img-cutter';
import VuePdfEmbed from "vue-pdf-embed";
import {Download} from '@element-plus/icons-vue'


export default {
  name: "NFT",
  computed: {
    userId() {
      return JSON.parse(sessionStorage.getItem('userObj')).id;
    },
    getRealName(){
      return JSON.parse(sessionStorage.getItem('userObj')).realName;
    },
    getId(){
      return JSON.parse(sessionStorage.getItem('userObj')).citizenId;
    },
    userObj(){
      return JSON.parse(sessionStorage.getItem('userObj'))
    },
  },
  // eslint-disable-next-line vue/no-unused-components
  components: {ImgCutter,VuePdfEmbed,Download},
  created() {
    this.getdata()
    this.getInfo()
    window.addEventListener('resize', this.getHeight)
  },
  data() {
    return {
      fullscreenLoading:false,
      loading:false,
      width:0,
      height:0,
      timer: null,
      drawer: false,
      detail: '',
      account: '',
      NFTstate: '',
      NFTtype: '',
      NFTname: '',
      numOfSplit:0,
      currentFile: [],
      CerUrl:'',
      nftObj:[],

      uploadNftVisible2: false,
      workKind:'',
      // nftKindOptions:[
      //   {key:'图片(.jpg .png)',val:'1'},{key:'文字(.txt)',val:'2'},{key:'音频(.wav .mp3)',val:'3'}
      // ],
      nftTypeOptions: [
        {key: '摄影作品(.jpg .png)', val: '1'}, {key: '文字作品(.txt)', val: '2'}, {key: '影视作品(.mp4)', val: '3'}, {
          key: '音乐作品(.wav .mp3)',
          val: '4'
        }, {key: '美术作品(.jpg .png)', val: '5'}
      ],
      nftTypeOptions2: [
        {key: '摄影作品(.jpg .png)', val: '1'}, {key: '文字作品(.txt)', val: '2'},  {
          key: '音乐作品(.wav .mp3)',
          val: '4'
        }, {key: '美术作品(.jpg .png)', val: '5'}
      ],
      // copyrightOwnerTypeOptions: [
      //   {key: '自然人', val: '1'}, {key: '企业法人', val: '2'}, {key: '机关法人', val: '3'}, {
      //     key: '事业单位法人',
      //     val: '4'
      //   }, {key: '社会团体法人', val: '5'}, {key: '其他', val: '6'},
      // ],
      // idTypeOptions: [
      //   {key: '身份证号', val: '1'}, {key: '军人身份证明', val: '2'}, {key: '户口本', val: '3'}, {
      //     key: '统一社会信用代码证书',
      //     val: '4'
      //   }, {key: '其他有效证件', val: '5'},
      // ],

      tagOptions: ['摄影', '绘画', '风景', '人物'],
      upLoadNftForm: {
        name: '',
        type: '',
        introduction: '',
        tag1: '',
        tag2: '',
        tag3: '',
        // copyrightOwnerType:'',
        // idType:'',
        fileList: [],
      },
      copyrightOwnerType:'1',
      copyrightOwnerName: '',
      idType:'1',
      copyrightOwnerId: '',
      upLoadNftRule: {
        name: [{required: true, message: "请输入nft名称", trigger: "blur"}],
        type: [{required: true, message: "请选择nft类别", trigger: "blur"}],
        introduction: [{required: true, message: "请输入作品简介", trigger: "blur"}],
        // copyrightOwnerType: [{required: true, message: "请选择所有权人身份类别", trigger: "blur"}],
        // copyrightOwnerName: [{required: true, message: "请输入所有权人名称", trigger: "blur"}],
        // idType: [{required: true, message: "请选择所有权人证件类型", trigger: "blur"}],
        // copyrightOwnerId: [{required: true, message: "请输入所有权人证件号码", trigger: "blur"}],
        fileList:[{required: true,trigger:'blur' ,message:'请上传文件'}]
      },
      TableData: [],
      uploadNftVisible: false,
      tableHeight:200
    }
  },
  methods: {
    getHeight () {
      this.tableHeight = window.innerHeight - 159
    },
    getInfo(){
      this.copyrightOwnerId=this.getId
      this.copyrightOwnerName=this.getRealName

    },

    addNft(){
      if(JSON.parse(sessionStorage.getItem('userObj')).isCertified==1){
        this.uploadNftVisible=true

      }else{
        this.$message({
          message: "请先实名认证",
          type: "error"
        });
      }
    },

    //上传nft表单清空
    upLoadClear(){
      this.upLoadNftForm.name=''
      this.upLoadNftForm.type=''
      this.upLoadNftForm.introduction=''
      this.upLoadNftForm.tag1=''
      this.upLoadNftForm.tag2=''
      this.upLoadNftForm.tag3=''
    },

    upLoad() {
      let form = new FormData()
      this.$refs.upLoadNftForm.validate((valid) => {
        if (!valid) {
          ElMessage({
            message: '请填写完整信息',
            type: 'error'
          })
        } else {
          this.fullscreenLoading=true
          var _t = this
          console.log("####")
          form.append("userId", JSON.parse(sessionStorage.getItem("userObj")).id)
          form.append("workName", this.upLoadNftForm.name)
          form.append("type", this.upLoadNftForm.type)
          form.append("introductionUrl", this.upLoadNftForm.introduction)
          form.append("copyrightOwnerType", parseInt(this.copyrightOwnerType))
          form.append("copyrightOwnerName", this.copyrightOwnerName)
          form.append("copyrightOwnerId", parseInt(this.copyrightOwnerId))
          form.append("idType", parseInt(this.idType))
          form.append("workTag1", this.upLoadNftForm.tag1)
          form.append("workTag2", this.upLoadNftForm.tag2)
          form.append("workTag3", this.upLoadNftForm.tag3)
          form.append("multipartFile", this.upLoadNftForm.fileList[0].raw)
          axios.post('http://120.48.51.66:8081/work/addNft', form).then( (response) =>{
            if (response.data.code == 200) {
              ElMessage({
                message: '添加成功',
                type: 'success'
              })
              _t.uploadNftVisible = false
              _t.fullscreenLoading=false
              _t.getdata()
              _t.upLoadClear()
              this.upLoadNftForm.fileList = ''
              this.upLoadNftForm.name = ''
              this.upLoadNftForm.tag3=''
              this.upLoadNftForm.tag2=''
              this.upLoadNftForm.tag1=''
              this.upLoadNftForm.introduction=''
            } else if (response.data.code == 19000){
              ElMessage({
                message: '请选择正确的文件类型！',
                type: 'error'
              })
              _t.fullscreenLoading=false
            } else {
              ElMessage({
                message: '错误',
                type: 'error'
              })
              _t.fullscreenLoading=false
            }
          })
          // this.upLoadNftForm.name = ''
        }
      })
      this.fullscreenLoading=false
      this.getdata()
    },

    upLoad2() {
      console.log("upload2 is exceded")
      // console.log(this.fileList[0].raw)
      let form = new FormData()
      this.$refs.upLoadNftForm.validate((valid) => {
        if (!valid) {
          ElMessage({
            message: '请填写完整信息',
            type: 'error'
          })
        } else {
          var _t = this
          console.log("####")
          form.append("userId", JSON.parse(sessionStorage.getItem("userObj")).id)
          form.append("workName", this.upLoadNftForm.name)
          form.append("type", this.upLoadNftForm.type)
          form.append("introductionUrl", this.upLoadNftForm.introduction)
          form.append("copyrightOwnerType", parseInt(this.copyrightOwnerType))
          form.append("copyrightOwnerName", this.copyrightOwnerName)
          form.append("copyrightOwnerId", parseInt(this.copyrightOwnerId))
          form.append("idType", parseInt(this.idType))
          form.append("workTag1", this.upLoadNftForm.tag1)
          if (this.upLoadNftForm.type == '1' || this.upLoadNftForm.type == '5'){
            form.append("count",9)
          } else{
            form.append("count",this.numOfSplit)
          }
          form.append("multipartFile", this.upLoadNftForm.fileList[0].raw)
          axios.post('http://120.48.51.66:8081/work/addNftPieces', form).then( (response)=> {
            if (response.data.code == 200) {
              ElMessage({
                message: '添加成功',
                type: 'success'
              })
              _t.uploadNftVisible = false
              _t.uploadNftVisible2 = false
              _t.fullscreenLoading=false
              _t.getdata()
              _t.upLoadClear()
              this.upLoadNftForm.fileList = ''
              this.upLoadNftForm.name = ''
              // this.upLoadNftForm.tag3=''
              // this.upLoadNftForm.tag2=''
              this.upLoadNftForm.tag1=''
              this.upLoadNftForm.introduction=''
            } else if (response.data.code == 19000){
              ElMessage({
                message: '请选择正确的文件类型！',
                type: 'error'
              })
              _t.fullscreenLoading=false
            } else {
              ElMessage({
                message: '错误',
                type: 'error'
              })
              _t.fullscreenLoading=false
            }
          })
          // this.upLoadNftForm.name = ''
        }
      })

    }
    ,
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handChange(file, fileList) {
      //一旦选中文件，就将该文件添加到currentFile中
      this.currentFile.push(file)
      this.upLoadNftForm.fileList = fileList
      // console.log(fileList[0].raw)
    },
    handleExceed() {
      this.$message.warning('只能上传1个文件哦');
    },
    beforeRemove(file) {
      return this.$confirm(`您确定要移除 ${file.name}吗？`);
    },
    //cutDown
    cut() {
      console.log("cut##")
    },
    //拆分
    handleChange2(file, fileList) {
      // this.sceneForm.uploadType = 0;
      this.currentFile.push(file)
      this.upLoadNftForm.fileList = fileList
      // console.log(fileList[0].raw)
      let fileSize = file.size / 1024 / 1024;
      // eslint-disable-next-line no-unused-vars
      fileSize = Math.floor(fileSize * 1000) / 1000; // 小数取整后三位
      this.asyncImgChecked(file).then(data => {
        if (data) {
          this.$refs.upload.submit();
        } else {
          this.upLoadNftForm.fileList = []
        }
      });
    },
    asyncImgChecked(file) {
      return new Promise(() => {
        let reader = new FileReader();
        reader.readAsDataURL(file.raw); // 必须用file.raw
        reader.onload =  ()=>{ // 让页面中的img标签的src指向读取的路径
          let img = new Image();
          img.src = reader.result;
          setTimeout(()=>{
            this.width=img.width
            this.height=img.height
          },300)
        };
      })
    },
    //选择状态
    changeNftState() {
      console.log('选择状态成功')
      this.getdata()
    },
    // 选择类型
    changeNftType() {
      console.log('选择类型成功')
      this.getdata()
    },

    //wbw
//搜索nft
    search() {
      this.getdata()
      console.log('搜索成功')
    },
    // 撤销nft
    revocation(temp) {
      console.log('撤销')
      console.log(temp)
      let form = new FormData();
      form.append("id", temp)

      axios.post('http://120.48.51.66:8081/work/deleteNft', form).then((response) => {
        if (response.data.code == 200) {
          ElMessage({
            message: "撤销nft成功",
            type: 'success'
          });
          console.log('撤销nft成功')

        } else {
          this.$message({
            message: "撤销nft失败",
            type: "error"
          });
        }
      });


    },

    go2Split() {
      this.uploadNftVisible = false
      this.uploadNftVisible2 = true
    },

    downloadCer(){
      window.location.href=this.CerUrl
    },

    async showDetail(filehash,workid) {
      this.detail = filehash
      this.drawer = true
      let txHash;
      let timeStamp;
      let blkHeight;
      //生成存证文件
        axios.get('http://120.48.51.66:8081/work/getNft',
            {
              params: {
                workId: workid,
              }
            }).then(async (response) => {
           if (response.data.code == 200){
             this.nftObj=response.data.data.nftInfo;
             this.CerUrl=response.data.data.nftInfo.certificateFileLocation;
             if(response.data.data.nftInfo.certificateFileLocation){
               return;
             }
             await confluxPortal.enable();
             this.account = confluxPortal.getAccount();
             if (this.account == ''){
               ElMessage({
                 message: '您还未连接conflux钱包插件',
                 type: 'warning'
               });
             } else if(this.account != this.userObj.pocket){
               ElMessage({
                 message: '请使用已绑定的钱包',
                 type: 'error'
               });
             }else {
               txHash=response.data.data.nftInfo.chainHash;
               const result =await conflux.getTransactionByHash(txHash);
               blkHeight=result.epochHeight[0];
               try {
                 const blk = await conflux.getBlockByHash(result.blockHash);
                 timeStamp = this.timestampToTime(blk.timestamp);
                 axios.get('http://120.48.51.66:8081/work/viewDetails',
                     {
                       params:{
                         workId:workid,
                         chainTime:timeStamp,
                         blockHeight:blkHeight
                       }
                     }).then(async (response) => {
                   if (response.data.code == 200){
                     ElMessage({
                       message: '生成成功',
                       type: 'success'
                     })
                   }else{
                     ElMessage({
                       message: '出现错误 请联系管理员',
                       type: 'error'
                     })
                   }
                 });
               }catch (e){
                 console.log(e);
                 ElMessage({
                   message: '区块哈希获取失败',
                   type: 'warning'
                 })
               }
             }
           }
        });
    },

    //上链
    async upChain(id) {
      var _t=this
      await confluxPortal.enable();
      this.account = confluxPortal.getAccount();
      this.fullscreenLoading=true
      if (this.account == '') {
        ElMessage({
          message: '您还未连接conflux钱包插件',
          type: 'warning'
        });
        this.fullscreenLoading=false
      }else if(this.account != this.userObj.pocket) {
        ElMessage({
          message: '请使用已绑定的钱包',
          type: 'error'
        });
        this.fullscreenLoading=false
      } else {
        axios.get('http://120.48.51.66:8081/work/getNft'
            , {
              params: {
                workId: id,
              }
            }).then(async (response) => {
          if (response.data.code == 200) {
            ElMessage({
              message: "开始上链，请稍后",
              type: "success"
            });
            if (response.data.data.chainHash === null) {
              this.fullscreenLoading=false
              ElMessage({
                message: "该作品已上链",
                type: "error"
              });
            } else {
              let filehash = response.data.data.nftInfo.fileHash;
              let workuri = response.data.data.nftInfo.workUri;
              let name = response.data.data.nftInfo.copyrightOwnerName;
              let Id = response.data.data.nftInfo.copyrightOwnerId;
              try {
                const called = ContractCopyrightSystemTransactions.contract.addWorks(
                    filehash,
                    workuri,
                    name,
                    Id,
                    JSON.parse(sessionStorage.getItem("userObj")).id
                )
                console.log(called)
                const transaction = await confluxPortal.sendTransaction({
                  from: this.account,
                  to: called.to,
                  data: called.data,
                })
                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                  const txHash = transaction.result;
                  const result = conflux.getTransactionByHash(txHash);
                  const blockheight = result.epochHeight;
                  console.log(transaction.result)
                  const blk = conflux.getBlockByHash(result.blockHash);
                  const timestamp = blk.timestamp;
                  const chaintime = timestamp + "(" + this.timestampToTime(timestamp) + ")"
                  let form = new FormData();
                  form.append('id', id);
                  form.append('chainHash', txHash)
                  form.append('status', '1')
                  form.append('blockHeight', blockheight)
                  form.append('chainTime', chaintime)
                  //上链成功后更新数据库
                  console.log(form)
                  axios.post('http://120.48.51.66:8081/work/uploadChain',
                      form)
                      .then(async (response) => {
                        if (response.data.code == 200) {
                          _t.getdata();
                          this.fullscreenLoading=false
                          ElMessage({
                            message: "修改数据库数据成功",
                            type: "success"
                          });
                        } else {
                          this.fullscreenLoading=false
                          ElMessage({
                            message: "修改数据库数据失败",
                            type: "error"
                          });
                        }
                      });
                }, 3000)
                ElMessage({
                  message: "上链成功",
                  type: "success"
                });
                this.getdata();
              } catch (e) {
                console.log(e)
                this.fullscreenLoading=false
                ElMessage({
                  message: "上链失败",
                  type: "error"
                });
              }
            }
          } else {
            this.fullscreenLoading=false
            ElMessage({
              message: "获取nft失败",
              type: "error"
            });
          }
        })
      }
      this.getdata()
    },

    timestampToTime(cjsj) {
      const date = new Date(cjsj * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = date.getDate() + ' '
      const h = date.getHours() + ':'
      const m = date.getMinutes() + ':'
      const s = date.getSeconds()
      return Y + M + D + h + m + s;
    },

    //获取数据
    getdata() {
      this.loading=true
      axios.get('http://120.48.51.66:8081/work/getNftInfo'
          , {
            params: {
              userId: this.userId,
              stringPara: this.NFTname,
              classification: this.NFTtype,
              status: this.NFTstate,
            }
          }).then((response) => {
            this.loading=false
        if (response.data.code == 200) {
          this.TableData = response.data.data.nftList
        } else {
          if(response.data.code==11100){
            console.log(11)
          }else{
            this.$message({
              message: "获取nft列表失败",
              type: "error"
            });          }
        }
        // eslint-disable-next-line no-unused-vars
      })
    }
  }
}

</script>
<style>
.digTop {
  border-radius: 8px 8px 8px 8px;
}

.imgCut{
  position: relative;
  left: 50px;
}

.card {
  width: 900px;
  position: relative;
  margin-left: 10px;
  margin-top: 10px;
}

.dialog {
  width: 1000px;
  position: relative;
  margin-left: 0px;
  padding-left: 20px;
  margin-right: 10px;
  margin-bottom: 20px;
  margin-top: 0px;
}

.seat {
  padding: 5px;
}

.choiceOfSplit{
  width: 600px;
  margin-left: 200px;
  border: none;
}
.tips{
  margin-left: -120px;
  width: 750px;
}
.CerPdf{
  margin-top: 10px;
  width: 100%;
  height: 100%;
}
.drawerTab{
  padding-left: 0px;
  margin-left: 0px;
  height: 100%;
  width: 100%;
}
</style>






